package com.lsc.record.core.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.lsc.record.core.entity.DmForm;
import com.lsc.record.core.entity.DmFormItem;
import com.lsc.record.core.entity.DmType;
import com.lsc.record.core.entity.DmTypeAttr;
import com.lsc.record.core.mapper.DmFormItemMapper;
import com.lsc.record.core.mapper.DmFormMapper;
import com.lsc.record.core.mapper.DmTypeMapper;
import com.lsc.record.core.service.FormServcie;
import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.spring.service.impl.ServiceImpl;

@Service
public class FormServiceImpl extends ServiceImpl<DmFormMapper, DmForm> implements FormServcie {

	@Resource
	private DmFormItemMapper itemMapper;

	@Resource
	private DmTypeMapper typeMapper;

	@Override
	public DmForm getById(Serializable id) {
		return this.mapper.selectOneWithRelationsById(id);
	};

	@Override
	public Optional<DmForm> getByIdOpt(Serializable id) {
		return Optional.ofNullable(this.getById(id));
	}

	@Override
	public void initForm(DmType typeRelation) {
		List<Row> formList = Db.selectListBySql("select * from dm_form where type_id=?", typeRelation.getId());
		if (formList.size() > 0) {
			return;
		}
		DmForm form = new DmForm();
		form.setName(typeRelation.getName());
		form.setTypeId(typeRelation.getId());
		this.save(form);

		List<DmTypeAttr> attrList = typeRelation.getItems();
		int sortIndex = 0;
		for (DmTypeAttr attr : attrList) {
			if (attr.getName().toLowerCase().contains("delete")) {
				continue;
			}
			DmFormItem formItem = new DmFormItem();
			formItem.setName(attr.getName());
			formItem.setLabel(attr.getTitle());
			formItem.setIsRequired(!attr.getDataNullable());
			formItem.setFormId(form.getId());
			formItem.setSortIndex(sortIndex);
			this.itemMapper.insert(formItem, true);
			sortIndex++;
		}
	}

	@Override
	public void saveCheck(DmForm data) throws Exception {
		if (StringUtils.isEmpty(data.getName())) {
			throw new Exception("表单名称不能为空");
		}

		if (StringUtils.isEmpty(data.getTypeId())) {
			throw new Exception("表单所属类型为必填");
		}

		Optional<DmType> typeOpt = Optional.ofNullable(typeMapper.selectOneById(data.getTypeId()));
		if (!typeOpt.isPresent()) {
			throw new Exception("表单所属类型不存在");
		}

	}
}
